<template>
  <div>
    <!-- 搜索部分 开始 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="运货师傅名字">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入"
          size="small"
          @keydown.enter.native="handleSearch()"
          @keydown.esc.native="handleClearSearch()"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input
          v-model="searchForm.phone"
          placeholder="请输入"
          size="small"
          @keydown.enter.native="handleSearch()"
          @keydown.esc.native="handleClearSearch()"
        ></el-input>
      </el-form-item>
      <el-form-item label="车牌号">
        <el-input
          v-model="searchForm.truckNum"
          placeholder="请输入"
          size="small"
          @keydown.enter.native="handleSearch()"
          @keydown.esc.native="handleClearSearch()"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="searchForm.state"
          placeholder="请选择"
          size="small"
          width="100"
        >
          <el-option :key="''" :label="'全部'" :value="''"></el-option>
          <el-option
            v-for="item in DriverStateEnum"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" size="small">
          <i class="el-icon-search"></i>
          查询
        </el-button>
        <el-button type="warning" @click="handleClearSearch" size="small">
          <i class="el-icon-search"></i>
          清除条件
        </el-button>
        <el-button type="danger" @click="handleDeleteByChosen" size="small">
          <i class="el-icon-delete-solid"></i>
          批量删除
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="
            initAddForm();
            dialogAddFormVisible = true;
          "
          size="small"
        >
          <i class="el-icon-plus"></i>
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 搜索部分结束 -->

    <!-- 表格部分 开始-->

    <el-table
      :data="tableList"
      style="width: 100%"
      border
      header-cell-class-name="tableHeaderCell"
      height="60vh"
      v-loading="loadingTable"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="name" label="名字" sortable width="120">
      </el-table-column>
      <el-table-column
        prop="gender"
        scope="row"
        label="性别"
        sortable
        width="80"
      >
        <template slot-scope="scope">
          {{ scope.row.gender }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" sortable width="180">
      </el-table-column>
      <el-table-column prop="truckNum" label="车牌号" sortable width="120">
      </el-table-column>
      <el-table-column
        prop="state"
        scope="row"
        label="状态"
        width="180"
        size="small"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.state"
            placeholder="请选择"
            @change="updateStatusById(scope.row)"
          >
            <el-option
              v-for="item in DriverStateEnum"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="所在位置" sortable width="250">
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleOpenEditDialog(scope.row)"
          >
            <i class="el-icon-edit-outline"></i>
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="removeDriverById(scope.row)"
          >
            <i class="el-icon-delete"></i>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格部分 结束-->

    <!-- 分页开始 -->
    <div class="page-container">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[5, 10, 30, 50]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </div>
    <!-- 分页结束 -->

    <!-- 添加司机的对话框-->
    <el-dialog
      title="新增运货师傅"
      :visible.sync="dialogAddFormVisible"
      width="40%"
      :before-close="beforeCloseDialog"
    >
      <el-form :model="addForm" :rules="addFormRule" ref="addForm">
        <el-form-item label="名字" prop="name" label-width="120">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" label-width="120">
          <el-input v-model="addForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" label-width="120">
          <el-radio-group v-model="addForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车牌号" prop="truckNum" label-width="120">
          <el-input v-model="addForm.truckNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在位置" prop="location" label-width="120">
          <el-input v-model="addForm.location" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="info"
          @click="dialogAddFormVisible = false"
          size="small"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleAddDriver(addForm)" size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑司机的对话框-->
    <el-dialog
      title="编辑司机信息"
      :visible.sync="dialogEditFormVisible"
      width="40%"
      :before-close="beforeCloseDialog"
    >
      <el-form :model="editForm" :rules="editFormRule" ref="editForm">
        <el-form-item label="名字" prop="name" label-width="120">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            @keydown.enter.native="handleUpdateDriver(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" label-width="120">
          <el-input
            v-model="editForm.phone"
            autocomplete="off"
            @keydown.enter.native="handleUpdateDriver(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" label-width="120">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车牌号" prop="truckNum" label-width="120">
          <el-input
            v-model="editForm.truckNum"
            autocomplete="off"
            @keydown.enter.native="handleUpdateDriver(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="所在位置" prop="location" label-width="120">
          <el-input
            v-model="editForm.location"
            autocomplete="off"
            @keydown.enter.native="handleUpdateDriver(editForm)"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="info"
          @click="dialogEditFormVisible = false"
          size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="handleUpdateDriver(editForm)"
          size="small"
          :disabled="disabledEditOkBtn"
          :loading="loadingEditOkBtn"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import driverApi from "@/api/driver.js";
import { DriverStateEnum } from "@/utils/constant.js";

export default {
  name: "Driver",

  data() {
    return {
      disabledEditOkBtn: false,
      loadingEditOkBtn: false,
      DriverStateEnum: [], // 枚举
      loadingTable: false, // 加载表格
      dialogAddFormVisible: false, // 添加的对话框是否可见
      dialogEditFormVisible: false,
      breadcrumbRoutes: [], // 面包屑路由
      searchForm: {
        // 查询表单
        name: "", // 名字
        phone: "", // 联系方式
        truckNum: "", // 车牌号
        state: "", // 状态ID
      },
      editForm: {
        // 编辑师傅的表单信息
        id: null,
        name: "",
        phone: "",
        gender: 1,
        state: "",
        truckNum: "",
        location: "",
      },
      addForm: {
        // 添加师傅的表单信息
        name: "",
        phone: "",
        gender: 1,
        truckNum: "",
        truck_num: "",
        location: "",
      },
      addFormRule: {
        name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/, //正则校验不用字符串
            message: "请填写正确的手机号码",
            trigger: "blur",
          },
        ],
        // gender: [
        //     { required: true, message: '性别不能为空', trigger: 'blur' },
        // ],
        truckNum: [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { max: 20, message: "密码不能超过20位", trigger: "blur" },
        ],
        location: [
          { required: true, message: "所在位置不能为空", trigger: "blur" },
        ],
      },
      editFormRule: {
        name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/, //正则校验不用字符串
            message: "请填写正确的手机号码",
            trigger: "blur",
          },
        ],
        // gender: [
        //     { required: true, message: '性别不能为空', trigger: 'blur' },
        // ],
        truckNum: [
          { required: true, message: "车牌号不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { max: 20, message: "密码不能超过20位", trigger: "blur" },
        ],
        location: [
          { required: true, message: "所在位置不能为空", trigger: "blur" },
        ],
      },
      ////////////////////////////////////////////////////////////////////////////////////////   需要向后台请求获取的数据
      statusList: [
        // 状态列表
        { id: 1, name: "工作中" },
        { id: 2, name: "工作中" },
        { id: 3, name: "休息中" },
        { id: 4, name: "请假中" },
      ],
      tableList: [], // 表格数据
      ////////////////////////////////////////////////////////////////////////////////////////  需要向后台请求获取的数据
      chosenTableList: [], // 选择的表格数据
      pageInfo: {
        pageNum: 1, // 当前页
        pageSize: 5, // 每一页的记录数量
        total: 20, // 总的记录数
      },
    };
  },
  created() {
    this.$bus.$emit("loadBreadcrumb");

    this.DriverStateEnum = DriverStateEnum;
    // 更新分页信息
    this.pageInfo.pageNum = Number(this.$route.params.pageNum) || 1;
    this.pageInfo.pageSize = Number(this.$route.params.pageSize) || 5;
    this.searchForm.pageNum = this.pageInfo.pageNum;
    this.searchForm.pageSize = this.pageInfo.pageSize;
    // 获取司机数据
    this.getTableList();
  },
  mounted() {},
  computed: {
    routePageNum() {
      return this.$route.query.pageNum;
    },
    routePageSize() {
      return this.$route.query.pageSize;
    },
  },
  methods: {
    beforeCloseDialog(done) {
      this.$confirm(`是否确认取消操作?`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        done();
      });
    },
    // 当点击搜索按钮
    handleSearch() {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: this.$route.pageNum,
          pageSize: this.$route.pageSize,
        },
      });
      this.getTableList(this.routePageNum, this.routePageSize);
    },
    // 清除筛选条件的查询
    handleClearSearch() {
      this.searchForm.id = "";
      this.searchForm.state = "";
      this.searchForm.name = "";
      this.searchForm.phone = "";
      this.handleSearch();
    },
    // 当选择表格某一项时
    handleSelectionChange(dataList) {
      this.chosenTableList = dataList;
    },
    // 切换页面时
    handleCurrentChange(pageNum) {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: pageNum,
          pageSize: this.$route.query.pageSize,
        },
      });
      this.getTableList(pageNum, this.routePageSize);
    },
    // 修改每一页记录显示数量时
    handlePageSizeChange(pageSize) {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: this.$route.query.pageNum,
          pageSize: pageSize,
        },
      });
      this.getTableList(1, pageSize);
    },

    // 根据师傅的 id 修改状态
    updateStatusById(driver) {
      driverApi.updateDriverById(driver).then(() => {
        this.$message.success("状态修改成功!");
        this.getTableList(this.routePageNum, this.routePageSize);
      });
    },

    handleDeleteByChosen() {
      // 如果没有选择司机, 则弹出提示并返回
      if (this.chosenTableList.length == 0) {
        return this.$message.warning("请先选择需要删除的司机");
      }
      // 提取出每个司机的ID
      const driverIds = [];
      this.chosenTableList.forEach((driver) => driverIds.push(driver.id));

      this.$confirm(`是否确认删除id为[${driverIds}]的这些司机？`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        driverApi.deleteDriverByIds(driverIds).then(() => {
          this.$message.success("删除成功!");
          setTimeout(() => {
            this.getTableList(1, this.routePageSize);
          }, 1000);
        });
      });
    },
    // 添加新司机
    handleAddDriver(driver) {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          driverApi.addDriver(driver).then(() => {
            this.$message.success("添加成功!");
            setTimeout(() => {
              this.getTableList(this.routePageNum, this.routePageSize);
            }, 1000);
            // 关闭窗口
            this.dialogAddFormVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    // 打开编辑司机的弹窗
    handleOpenEditDialog(driver) {
      this.editForm.name = driver.name;
      this.editForm.id = driver.id;
      this.editForm.phone = driver.phone;
      this.editForm.gender = driver.gender;
      this.editForm.state = driver.state;
      this.editForm.truckNum = driver.truckNum;
      this.editForm.location = driver.location;
      this.dialogEditFormVisible = true;
    },
    // 初始化表单信息
    initAddForm() {
      this.addForm.name = "";
      this.addForm.phone = "";
      this.addForm.gender = "男";
      this.addForm.truckNum = "";
      this.addForm.location = "";
    },
    // 更新司机信息
    handleUpdateDriver(driver) {
      // 禁用 按钮
      this.disabledEditOkBtn = true;
      // 加载按钮
      this.loadingEditOkBtn = true;
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          driverApi.updateDriverById(driver).then(() => {
            this.$message.success("更新成功!");
            setTimeout(() => {
              this.dialogEditFormVisible = false;
              this.getTableList(this.routePageNum, this.routePageSize);
            }, 1000);
          });
        } else {
          return false;
        }
      });
      setTimeout(() => {
        this.loadingEditOkBtn = false;
        this.disabledEditOkBtn = false;
      }, 1200);
    },
    ////////////////////////////////// 请求数据 的方法 ///////////////////////////////
    getTableList(pageNum = 1, pageSize = 5) {
      this.loadingTable = true;
      driverApi
        .getPage({ ...this.searchForm, pageNum, pageSize })
        .then((response) => {
          const { pageInfo } = response.data;
          // 记录表格数据
          this.tableList = pageInfo.driverList;
          // 记录分页数据
          this.pageInfo.pageNum = pageInfo.pageNum;
          this.pageInfo.pageSize = pageInfo.pageSize;
          this.pageInfo.total = pageInfo.total;
          setTimeout(() => {
            this.loadingTable = false;
          }, 300);
        });
    },
    removeDriverById(driver) {
      this.$confirm(`是否确认删除司机[${driver.name}]？`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        driverApi.deleteDriverByIds([driver.id]).then(() => {
          this.$message.success("删除成功!");
          setTimeout(() => {
            this.getTableList(1, this.routePageSize);
          }, 1000);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  margin-top: 20px;
  text-align: center;
}
:deep .tableHeaderCell{
    background: #e2e9a2 !important;
    color: #495069;
}
</style>